<?php

namespace addons\xilumarket;

use addons\xilumarket\controller\WeixinMini;
use app\admin\model\xilumarket\order\OrderDelivery;
use app\common\library\Menu;
use app\common\model\User;
use app\common\model\xilumarket\MoneyLog;
use app\common\model\xilumarket\Order;
use app\common\model\xilumarket\OrderDivide;
use app\common\model\xilumarket\UserAccount;
use app\common\model\xilumarket\UserFocus;
use app\common\model\xilumarket\UserMessage;
use app\common\model\xilumarket\Withdraw;
use think\Addons;
use think\Db;
use think\db\Expression;
use think\Exception;
use think\exception\PDOException;
use think\Log;

/**
 * 插件
 */
class Xilumarket extends Addons
{

    /**
     * 插件安装方法
     * @return bool
     */
    public function install(){
        $menu = include ADDON_PATH . 'xilumarket' . DS . 'data' . DS . 'menu.php';
        Menu::create($menu);
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        Menu::delete("xilumarket");
        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        Menu::enable("xilumarket");
        return true;
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        Menu::disable("xilumarket");
        return true;
    }

    /**
     * 添加命令行扩展
     */
    public function appInit()
    {
        // 公共方法
        require_once __DIR__ . '/helper.php';

        //h5二维码
        if(!class_exists("\PHPQRCode\QRcode")){
            \think\Loader::addNamespace('PHPQRCode', ADDON_PATH . 'xilumarket' . DS . 'library' . DS . 'PHPQRCode' . DS.'lib'.DS.'PHPQRCode'.DS);
        }

        \think\Console::addDefaultCommands([
            'addons\\xilumarket\\chatprograms\\GatewayWorker\\start',
        ]);
    }

    /**
     * 购买金额-创建冻结数据
     */
    public function xilumarketOrderFreeze(Order $order){
        //
        $divide = OrderDivide::where('order_id',$order->id)->find();
        if($divide && $divide->status != 1){
            return false;
        }
        try {
            $divide = OrderDivide::create([
                'user_id'   =>  $order->seller_user_id,
                'order_id'  =>  $order->id,
                'order_money'=> $order->pay_price,
                'status'    => '1'
            ]);

            MoneyLog::create([
                'user_id' => $order->seller_user_id,
                'divide_id'=>$divide->id,
                'money' => $order->pay_price,
                'memo'   => '用户下单',
                'status' => 0,
                //'content' => "您的\"{$job->job_name}\"岗位有新的投递，请及时处理。",
                'extra' => json_encode([
                    'type'          =>  1,//下单佣金
                    'order_id'      =>  $order->id,
                    'user_id'       =>  $order->user_id,
                    'order_no'      =>  $order->order_no,
                    'product_name'  =>  $order->order_product[0]->product_name,
                    'buyer_nickname'=>  $order->user ? $order->user->nickname :'',
                    'buyer_avatar'   =>  $order->user?$order->user->avatar:'-'
                ])
            ]);
        }catch (Exception|PDOException $e){

        }

    }

    /**
     * 解冻
     */
    public function xilumarketThawDivide(Order $order){
        $divide = OrderDivide::where('order_id',$order->id)->find();
        if(!$divide || $divide->status != 1){
            return false;
        }
        
        // ↓ ----------------------------配送费结算
        $orderDelivery = OrderDelivery::where(['order_id' => $order->id])->find();
        var_dump(1111111111);
        if($orderDelivery){
            $duserAccount = UserAccount::addAccount($orderDelivery->user_id);
            MoneyLog::create([
                'type' => 1,
                'user_id' => $orderDelivery->user_id,
                'divide_id' => $divide->id,
                'money' => $orderDelivery->fee,
                'memo'  => '配送费',
                'before'  =>  $duserAccount->money,
                'after'  =>  $duserAccount->money + $orderDelivery->fee,
                'status'    => 1
            ]);
            var_dump($orderDelivery->fee);
            $duserAccount->money = new Expression("money+".$orderDelivery->fee);
            $duserAccount->total_money = new Expression("total_money+".$orderDelivery->fee);
            $duserAccount->save();
        }
        // ↑ ----------------------------配送费结算

        $moneyLogs = MoneyLog::where('divide_id',$order->id)->select();
        foreach ($moneyLogs as $moneyLog){
            $moneyLog->status = 1;
            $moneyLog->save();
            $userAccount = UserAccount::addAccount($moneyLog->user_id);
            $userAccount->money = new Expression("money+".$order->pay_price);
            $userAccount->total_money = new Expression("total_money+".$order->pay_price);
            $userAccount->save();
        }
        //佣金解冻
        $divide->status = 2;
        $divide->unfreezetime = time();
        $divide->save();
        return true;
    }

    /**
     * 申诉成功-佣金作废，退款-订单作废
     * @param Object $appeal
     */
    public function xilumarketAppealSuccess($appeal){
        $divide = OrderDivide::where('order_id',$appeal->order_id)->find();
        if($divide->status == 2){
            throw new Exception("佣金已解冻");
        }
        if($divide->status == 0){
            throw new Exception("佣金已失效");
        }
        $order = Order::where('id',$appeal->order_id)->find();
        if($order->state == 6){
            throw new Exception("订单已退款");
        }
        #1.佣金失效
        $divide->status = 0;
        $divide->save();
        #2.订单已退款成功
        $order->refund_status = 2;
        $order->refund_time = time();
        $order->save();
        #3.佣金记录作废
        MoneyLog::where('divide_id',$order->id)->update(['status'=>-1]);
        #4.客户退款
        // 增加售后单变动记录
        \app\common\model\xilumarket\AftersaleLog::operate_add($order, null, session('admin'), 'admin', [
            'title' => '退款申诉通过',
            'description' => '退款申诉通过，订单已退款',
            'images' => []
        ]);
        #第三方退款走这里
        $weixin = new WeixinMini();
        $res = $weixin->refund($appeal->id,$order->total_price,'appeal');
        if(!$res['status']){
            throw new Exception($res['msg']);
        }
        return true;

    }

    /**
     * 提现
     */
    public function xilumarketWithdraw(Withdraw $withdraw){
        MoneyLog::create([
            'type'      => 2,
            'user_id' => $withdraw->user_id,
            'withdraw_id'=>$withdraw->id,
            'money' => '-'.$withdraw->money,
            'memo'   => '用户提现',
            'status' => 1, //正常
            //'content' => "您的\"{$job->job_name}\"岗位有新的投递，请及时处理。",
            'extra' => json_encode([
                'type'          =>  2,//提现
                'status'        => 1,//审核中
                'withdraw_id'      =>  $withdraw->id,
                'user_id'       =>  $withdraw->user_id,
                'order_no'      =>  $withdraw->order_no
            ])
        ]);
    }

    /**
     * 提现通过
     */
    public function xilumarketWithdrawAgree($withdraw){
        $money_log = MoneyLog::where('type',2)->where('withdraw_id',$withdraw->id)->find();
        if(!$money_log){
            throw new Exception("提现日志不存在");
        }
        $extra = json_decode($money_log->extra,true);
        $extra['status'] = 2;//审核通过;
        $money_log->extra = json_encode($extra);
        $money_log->save();
        return true;
    }

    /**
     * 提现拒绝
     */
    public function xilumarketWithdrawRefuse($withdraw){
        $money_log = MoneyLog::where('type',2)->where('withdraw_id',$withdraw->id)->find();
        if(!$money_log){
            throw new Exception("提现日志不存在");
        }
        $extra = json_decode($money_log->extra,true);
        $extra['status'] = 3;//审核未通过;
        $money_log->extra = json_encode($extra);
        $money_log->save();
        $user_account = UserAccount::addAccount($withdraw->user_id);
        $user_account->money = new Expression("money+".$withdraw->money);
        $user_account->save();
        return true;
    }

    /**
     * 互动消息
     * @param UserFocus $user
     */
    public function xilumarketFocusMessage(UserFocus $userFocus){
        $user = User::where('id',$userFocus['user_id'])->find();
        $user_account = UserAccount::addAccount($userFocus->focus_user_id);
        $model = UserMessage::create([
            'user_id'      =>   $userFocus->focus_user_id,
            'module_type'  =>   UserMessage::MODULE_TYPE_INTERACTION,
            'type'         =>   UserMessage::TYPE_INTERACTION,
            'title'        =>   '用户关注',
            'content' => sprintf('"%s"已关注了您', $user->nickname),
            'extra' => [
                'user_id'=>$userFocus->user_id,
                'nickname'=>$user->nickname,
                'avatar'  =>$user->avatar,
                'focus_user_id'=>$userFocus->focus_user_id
            ]
        ]);
        $user_account->save(['user_message'=>Db::raw('user_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
    }

    /**
     * 下单成功，卖家收到消息
     * @param Order $order
     */
    public function xilumarketOrderPay(Order $order){
        $user_account = UserAccount::addAccount($order->seller_user_id);
        $model = UserMessage::create([
            'user_id'      =>   $order->seller_user_id,
            'module_type'  =>   UserMessage::MODULE_TYPE_SYSTEM,
            'type'         =>   UserMessage::TYPE_NEW_ORDER,
            'title'        =>   '买家下单成功',
            'content' => sprintf('买家"%s"已购买"%s"商品，请及时处理', $order->user->nickname, $order->order_product[0]['product_name']),
            'extra' => [
                'order_id'=>$order->id,
                'product_id'=>$order->order_product[0]['product_id'],
                'user_id'=>$order->user_id,'product_name'=>$order->order_product[0]['product_name']
            ]
        ]);
        $user_account->save(['system_message'=>Db::raw('system_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
    }

    /**
     * 下单成功取消，通知卖家
     * @param Order $order
     */
    public function xilumarketOrderCancel(Order $order){
        $user_account = UserAccount::addAccount($order->seller_user_id);
        $model = UserMessage::create([
            'user_id'      =>   $order->seller_user_id,
            'module_type'  =>   UserMessage::MODULE_TYPE_SYSTEM,
            'type'         =>   UserMessage::TYPE_CANCEL_ORDER,
            'title'        =>   '买家取消购买订单',
            'content' => sprintf('买家"%s"已取消"%s"商品购买', $order->user->nickname, $order->order_product[0]['product_name']),
            'extra' => [
                'order_id'=>$order->id,
                'product_id'=>$order->order_product[0]['product_id'],
                'user_id'=>$order->user_id,'product_name'=>$order->order_product[0]['product_name']
            ]
        ]);
        $user_account->save(['system_message'=>Db::raw('system_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
    }

    /**
     * 下单完成，通知卖家
     * @param Order $order
     */
    public function xilumarketOrderFinish(Order $order){
        $user_account = UserAccount::addAccount($order->seller_user_id);
        $model = UserMessage::create([
            'user_id'      =>   $order->seller_user_id,
            'module_type'  =>   UserMessage::MODULE_TYPE_SYSTEM,
            'type'         =>   UserMessage::TYPE_FINISH_ORDER,
            'title'        =>   '买家完成订单',
            'content' => sprintf('买家"%s"已确认完成"%s"商品，请及时查看资金情况', $order->user->nickname, $order->order_product[0]['product_name']),
            'extra' => [
                'order_id'=>$order->id,
                'product_id'=>$order->order_product[0]['product_id'],
                'user_id'=>$order->user_id,'product_name'=>$order->order_product[0]['product_name']
            ]
        ]);
        $user_account->save(['system_message'=>Db::raw('system_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
    }


    /**
     * 发货成功，通知买家
     * @param Order $order
     */
    public function xilumarketOrderFreight(Order $order){
        $user_account = UserAccount::addAccount($order->user_id);
        $model = UserMessage::create([
            'user_id'      =>   $order->user_id,
            'module_type'  =>   UserMessage::MODULE_TYPE_SYSTEM,
            'type'         =>   UserMessage::TYPE_FREIGHT_ORDER,
            'title'        =>   '卖家发货通知',
            'content' => sprintf('卖家"%s"已完成"%s"订单的发货，请及时查看物流信息', $order->seller->nickname, $order->order_no),
            'extra' => [
                'order_id'=>$order->id,
                'order_no'=>$order->order_no,
                'product_id'=>$order->order_product[0]['product_id'],
                'user_id'=>$order->user_id,
                'product_name'=>$order->order_product[0]['product_name']
            ]
        ]);
        $user_account->save(['system_message'=>Db::raw('system_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
    }

    /**
     * 订单自动取消，通知买家
     * @param Order $order
     */
    public function xilumarketOrderAutoCancel(Order $order){
        $user_account = UserAccount::addAccount($order->user_id);
        $model = UserMessage::create([
            'user_id'      =>   $order->user_id,
            'module_type'  =>   UserMessage::MODULE_TYPE_SYSTEM,
            'type'         =>   UserMessage::TYPE_AUTO_CANCEL_ORDER,
            'title'        =>   '订单取消通知',
            'content' => sprintf('您的"%s"订单的因超时未付款，已被取消', $order->order_no),
            'extra' => [
                'order_id'=>$order->id,
                'order_no'=>$order->order_no,
                'product_id'=>$order->order_product[0]['product_id'],
                'user_id'=>$order->user_id,
                'product_name'=>$order->order_product[0]['product_name']
            ]
        ]);
        $user_account->save(['system_message'=>Db::raw('system_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
    }
    /**
     * 订单自动完成，通知买家
     * @param Order $order
     */
    public function xilumarketOrderAutoFinish(Order $order){
        $user_account = UserAccount::addAccount($order->user_id);
        $model = UserMessage::create([
            'user_id'      =>   $order->user_id,
            'module_type'  =>   UserMessage::MODULE_TYPE_SYSTEM,
            'type'         =>   UserMessage::TYPE_AUTO_FINISH_ORDER,
            'title'        =>   '订单完成通知',
            'content' => sprintf('您的"%s"订单的因超时未确认收货，已自动确认收货', $order->order_no),
            'extra' => [
                'order_id'=>$order->id,
                'order_no'=>$order->order_no,
                'product_id'=>$order->order_product[0]['product_id'],
                'user_id'=>$order->user_id,
                'product_name'=>$order->order_product[0]['product_name']
            ]
        ]);
        $user_account->save(['system_message'=>Db::raw('system_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
    }

}
